package cn.cf.kxx.tools;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.serotonin.modbus4j.sero.util.ArrayUtils;

import org.apache.commons.lang3.RandomStringUtils;

import java.lang.reflect.Type;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.cf.kxx.model.dev.Hold;

public class Tools {
//    public static ExecutorService threaPool = Executors.newFixedThreadPool(3);

    private static final String URL = "http://43.138.50.38:8081/lrrigate";

    public static String findDeviceByDevBh = URL + "/screen/device/findDeviceByDevBh";//  查设备的url
    public static String findDeviceFarm = URL + "/screen/farm/findFarm?parentId=";//  查设备的农场
    public static String findDeviceWeather = URL + "/screen/weather/findDeviceWeather";//  查设备的天气
    public static String uploadDevice = URL + "/screen/device/updateDeviceByDevBh";//  更新设备数据
    public static String uploadValDevice = URL + "/screen/device/updateValDevice";//更新阀门列表

    public static String getDeviceId(Context context){
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }


    public static boolean isWifiProxy(Context context) {
        final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        int proxyPort;
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        } else {
            proxyAddress = android.net.Proxy.getHost(context);
            proxyPort = android.net.Proxy.getPort(context);
        }
        return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
    }

    /**
     * 获取连接类型
     *
     * @param type
     * @return
     */
    public static String getConnectionType(int type) {
        String connType = "";
        if (type == ConnectivityManager.TYPE_MOBILE) {
            connType = "3-4G网络数据";
        } else if (type == ConnectivityManager.TYPE_WIFI) {
            connType = "WIFI网络";
        }
        return connType;
    }

    public static Gson gson = new Gson();
    static Type type;

    public static Type getHoldType(){
        if(type == null){
            type = new TypeToken<Hold>() {}.getType();
        }
        return type;
    }

    public static String getDevBh(String bh){
        LocalDate localDate = LocalDate.now();
        StringBuilder sb = new StringBuilder();
        sb.append(localDate.getYear());
//        if(localDate.getMonthValue() < 10){
//            sb.append("0"+localDate.getMonthValue());
//        }else{
//            sb.append(localDate.getMonthValue());
//        }
        sb.append(bh);
//        if(localDate.getDayOfMonth() < 10){
//            sb.append("0"+localDate.getMonthValue());
//        }else{
//            sb.append(localDate.getDayOfMonth());
//        }
//        if(sb.toString().length() != 12){
//            sb.append(RandomStringUtils.randomNumeric(4));
//        }
        return sb.toString();
    }


    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static boolean isNumber(String str) {
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 小端取反
     * @param bytes
     * @return
     */
    public static float IEE754Parser(byte[] bytes){
        byte linshi = bytes[0];
        bytes[0] = bytes[1];
        bytes[1] = linshi;
        linshi = bytes[2];
        bytes[2] = bytes[3];
        bytes[3] = linshi;
       return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
    }

    /**
     * 小端
     * @param bytes
     * @return
     */
    public static float TwoByteParserLit(byte[] bytes){
        byte linshi = bytes[0];
        bytes[0] = bytes[1];
        bytes[1] = linshi;
        return ((float) ArrayUtils.byteRangeValue(bytes,0,bytes.length) / 10);
    }


    /**
     * 小端
     * @param bytes
     * @return
     */
    public static float TwoByteParserBig(byte[] bytes){
        return ((float) ArrayUtils.byteRangeValue(bytes,0,bytes.length) / 10);
    }

    public static LocalDateTime dateToDateTime(Date date) {
        Instant instant = date.toInstant();
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static String YYYYMMDDHHMM = "yyyy-MM-dd HH:mm";
    public static String getForMatTime(Date date, String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDateTime localDateTime = dateToDateTime(date);
        return formatter.format(localDateTime);
    }

    /**
     * 判断网络是否连接
     */
    public static boolean isConnectIsNormal(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            Log.e(MQTTUtils.TAG, "当前网络名称：" + name);
            return true;
        } else {
            Log.e(MQTTUtils.TAG, "没有可用网络");
            return false;
        }
    }
}
